<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use App\Http\Model\FinanceWithdrawOrder;
use App\Http\Model\FinanceKk;
use App\Http\Model\SystemConfig;
class GiftKkRepair extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'giftKkRepair';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '送礼金币数据修复';
    protected $systemConfigModel;
    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        $this->systemConfigModel = new SystemConfig();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        do {
            $timeSt = '2023-08-16 17:11:00';
            $timeEd = '2023-08-16 17:46:00';

            //清理所有时间段内的
            DB::table('finance_kk_stream')
                ->where('change_time', '>=', $timeSt)
                ->where('change_time', '<=', $timeEd)
                ->where('kk_type', 0)
                ->delete();

            DB::table('finance_kk_stream')
                ->where('change_time', '>=', $timeSt)
                ->where('change_time', '<=', $timeEd)
                ->where('kk_type', 14)
                ->delete();

            DB::table('finance_kk_stream')
                ->where('change_time', '>=', $timeSt)
                ->where('change_time', '<=', $timeEd)
                ->where('kk_type', 11)
                ->delete();

            DB::table('finance_kk_stream')
                ->where('change_time', '>=', $timeSt)
                ->where('change_time', '<=', $timeEd)
                ->where('kk_type', 36)
                ->delete();

            //所有的送礼记录
            $list = DB::table('gift_stream')
                ->where('change_timestamp', '>=', strtotime($timeSt))
                ->where('change_timestamp', '<=', strtotime($timeEd))
                ->get();
            $list = $this->objToArray($list);

//            $config = config('pay');
//            $charm_to_kk = $config['wallet_change_ratio']['charm_to_kk'];
            $config=$this->systemConfigModel->getDefaultSystemConfig();
            //用户分成比例
            $charm_to_kk = $config['charm_to_kk']['value'];
            foreach($list as $val) {
                $kk_value = intval($val['gift_price'] * $val['gift_num'] * $charm_to_kk);
                if($kk_value < 1) {
                    continue;
                }

                if(!empty($val['room_id'])) {
                    $kk_desc = $config['wallet_change_desc']['room_gift_receive_kk'];
                }else{
                    $kk_desc = $config['wallet_change_desc']['gift_receive_kk'];
                }

                $room_id = $val['room_id'];

                $kk_type = 0;

                $user_id = $val['user_id'];
                $from_user_id = $val['from_user_id'];


                DB::beginTransaction();
                try {
                    DB::table("finance_kk_stream")->insert([
                            "user_id" => $user_id,
                            "room_id" => $room_id,
                            "kk_value" => $kk_value,
                            "from_user_id" => $from_user_id,
                            "kk_type" => $kk_type,
                            "kk_desc" => $kk_desc,
                            "kk_balance" => 0,
                            "change_timestamp" => $val['change_timestamp'],
                            "change_time" => date("Y-m-d H:i:s", $val['change_timestamp']),
                        ]);

                    DB::commit();
                } catch (\Exception $e) {
                    echo $e->getMessage();
                    DB::rollBack();
                }
        
            }

            //用户余额
            $userList = DB::table('finance_kk_stream')
                ->where('change_time', '>=', $timeSt)
                ->select('user_id')
                ->distinct()
                ->get();
            $userList = $this->objToArray($userList);

            foreach($userList as $val) {
                $userId = $val['user_id'];
                //统计值
                $newNum = DB::table('finance_kk_stream')
                    ->select(DB::raw('SUM(kk_value) as kk_value'))
                    ->where('user_id', $userId)
                    ->first();
                $newNum = $this->objToArray($newNum);
                $newNum = empty($newNum['kk_value']) ? 0 : $newNum['kk_value'];
                if($newNum >= 0) {
                    DB::table("finance_wallet")
                        ->where('user_id', '=', $userId)
                        ->update(['kk_balance'=>$newNum]);
                }else{
                    echo $userId.' 用户余额为负数'. $newNum;
                    echo ' ';
                }
                Redis::DEL( 'CACHE:FINANCE:USER:WALLET:' . $userId);
            }

            //用户每日收益
            $timeSt = '2023-08-16 00:00:00';
            $timeEd = '2023-08-17 00:00:00';
            foreach($userList as $val) {
                $userId = $val['user_id'];
                //统计值
                $newNum = DB::table('finance_kk_stream')
                    ->select(DB::raw('SUM(kk_value) as kk_value'))
                    ->where('change_time', '>=', $timeSt)
                    ->where('change_time', '<', $timeEd)
                    ->where('user_id', $userId)
                    ->first();
                $newNum = $this->objToArray($newNum);
                $newNum = empty($newNum['kk_value']) ? 0 : $newNum['kk_value'];
                $redisDay = 'CACHE:FINANCE:USER:KK:TODAY:20230816';
                Redis::HINCRBY($redisDay, $userId, $newNum);
                if (Redis::TTL($redisDay) < 0){
                    Redis::EXPIRE($redisDay, 25*3600);
                }
            }

        } while (false);

    }
    //返回数组
    public function objToArray($document)
    {
        return json_decode(json_encode($document), true);
    }

}